(function($){
    $.fn.wdAutoSuggest = function(settings) {
        var resultCount = 0;
        var resultSelected = -1;
        
        return this.each(function(index) {
            $(this).keypress(function(e) {
                var keyCode = (e.keyCode ? e.keyCode : e.which);
                // check for an ENTER
                if (keyCode == 13) {
                    OnEnterClick();
                }
            });
            // -------------------------------->
            $(this).keyup(function(e) {
                // Temp
                //return;
                
                
                var _searchTerm = $.trim($(this).val());
                var _length = _searchTerm.length;
                //get keyCode (window.event is for IE)
                var keyCode = e.keyCode || window.event.keyCode;
        
                // check an treat up and down arrows
                if (OnUpDownClick(keyCode)) {
                    return;
                }
                // check for an ENTER 
                if (keyCode == 13) {
                    return false;
                }
                else if (_length > 2) {
                    $.ajax(
                            {
                                type: "GET",
                                url: "search/index",
                                data: "searchTerm=" + _searchTerm,
                                dataType: "json",
                                cache: "true",
                                beforeSend: function() {
                                    ShowLoaders();
                                    $(".aui-dropdown").html("");
                                },
                                complete: function() {
                                    HideLoaders();
                                },
                                success: function(response) {
                                    if (response != null) {
                                        if (response.rows[0] != undefined) {
                                            PopulateResults(response);
                                            resultCount = $(".aui-dropdown > OL").size();
                                            // on mouse over clean previous selected and set a new one
                                            $(".aui-dropdown > ol > li").mouseover(function() {
                                                $(".aui-dropdown > ol >li").each(function() {
                                                    this.className = "unselected";
                                                    $(this).children().addClass("unselected");
                                                    $(this).children().removeClass("selected");
                                                });
                                                this.className = "selected";
                                                $(this).children().addClass("selected");
                                                $(this).children().removeClass("unselected");
                                            })
                                        }
                                        else {
                                            HideSearchResults();
                                        }
                                    }
                                    else {
                                        HideSearchResults();
                                    }
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    HideSearchResults();
                                    //alert("Error:\n" + errorThrown);
                                }
                            }); // ajax Close
                }   //if close
                else {
                    HideSearchResults();
                    HideLoaders();
                }
                
                if ($('#searchBox').val().length == 0) {
                    // if the user removed all of the text, reset the search
                         resetSearch();
                    }
            }); //keyup close
            
            $(".aui-dropdown").focusout(function() {
                HideSearchResults();
            }); //focusin close

            $(document).keydown(function(e) {
                if (e.which == 27) {
                    HideSearchResults();
                }
            }); //keydown close

            $(document).click(function(e) {
                var screenX = e.clientX;
                var screenY = e.clientY;
                var left = $(".aui-dropdown").offset().left;
                var top = $(".aui-dropdown").offset().top;
                var ctrlWidth = parseInt($(".aui-dropdown").css("width"));
                var ctrlHeigth = parseInt($(".aui-dropdown").css("height") == "auto" ? $(".aui-dropdown").height() : $(".aui-dropdown").css("height"));
                var diffY = Math.abs(screenY - ctrlHeigth);
                var diffX = Math.abs(screenX - ctrlWidth);
                if (diffX > left && diffY > top)
                    HideSearchResults();
                else if (screenY < top)
                    HideSearchResults();
                else if (screenX < left)
                    HideSearchResults();
            });
    
            $("#imgSearch").click(function(){
                resetSearch();
            });
            $("#searchBox").click(function(){
                resetSearch();
            });
        });
        //==================================== private function =====================================
        function ShowLoaders() {
            $("#searchBox").addClass("ac_loading");
        }

        function HideLoaders() {
            $("#searchBox").removeClass("ac_loading");
        }

        function PopulateResults(response) {
            $("#divUserDetails").fadeOut()
            var htmlBuffer, name, dept, job, room, recordType, accountName, userdetailsUrl, dataSetUser, dataSetOther,datasetJobtitle;
            htmlBuffer = "";
            $(".aui-dropdown").html("");
            dataSetUser = response.rows;

            for (var item in dataSetUser) {
                var userDept, userJob;
                recordType = dataSetUser[item].recordType;
                accountName = (dataSetUser[item].samaccountName == null ? "" : dataSetUser[item].samaccountName);
                userDept = (dataSetUser[item].dept == null ? "" : dataSetUser[item].Dept);
                userJob = (dataSetUser[item].job == null ? "" : dataSetUser[item].Job);
                if (recordType == "user") {
                    name = dataSetUser[item].name;
                    if (accountName == "")
                        userdetailsUrl = "#";
                    else
                        userdetailsUrl = "listusersql.asp?userid=" + accountName + "";
                    
                    htmlBuffer = htmlBuffer + '<ol>';
                    htmlBuffer = htmlBuffer + '<li>';
                    htmlBuffer = htmlBuffer + '<a href="' + userdetailsUrl + '" class="content-type-userinfo">';
                    htmlBuffer = htmlBuffer + '<span title="' + name + '">' + name;
                    if (userDept != "")
                        htmlBuffer = htmlBuffer + '<b> | </b>' + userDept;
                    if (userJob != "")
                        htmlBuffer = htmlBuffer + '<b> | </b>' + userJob;
                    htmlBuffer = htmlBuffer + '<var style="display: none;">…</var>';
                    htmlBuffer = htmlBuffer + '</span>';
                    htmlBuffer = htmlBuffer + '</a>';
                    htmlBuffer = htmlBuffer + '</li>';
                    htmlBuffer = htmlBuffer + '</ol>';
                }
                else if (recordType == "department") {
                dept = dataSetUser[item].name;
                    htmlBuffer = htmlBuffer + '<ol>';
                    htmlBuffer = htmlBuffer + '<li>';
                    htmlBuffer = htmlBuffer + '<a href="#" class="content-type-deptinfo">';
                    htmlBuffer = htmlBuffer + '<span title="' + dept + '">' + dept + '';
                    htmlBuffer = htmlBuffer + '<var style="display: none;">…</var>';
                    htmlBuffer = htmlBuffer + '</span>';
                    htmlBuffer = htmlBuffer + '</a>';
                    htmlBuffer = htmlBuffer + '</li>';
                    htmlBuffer = htmlBuffer + '</ol>';
                }
                else if (recordType == "jobtitle") {
                job = dataSetUser[item].name;
                htmlBuffer = htmlBuffer + '<ol>';
                htmlBuffer = htmlBuffer + '<li>';
                htmlBuffer = htmlBuffer + '<a href="#" class="content-type-jobinfo">';
                htmlBuffer = htmlBuffer + '<span title="' + job + '">' + job + '';
                htmlBuffer = htmlBuffer + '<var style="display: none;">…</var>';
                htmlBuffer = htmlBuffer + '</span>';
                htmlBuffer = htmlBuffer + '</a>';
                htmlBuffer = htmlBuffer + '</li>';
                htmlBuffer = htmlBuffer + '</ol>';
            }
            else if (recordType == "room") {
                room = dataSetUser[item].name;
                htmlBuffer = htmlBuffer + '<ol>';
                htmlBuffer = htmlBuffer + '<li>';
                htmlBuffer = htmlBuffer + '<a href="meetingroom.asp?roomId=' + accountName + '" class="content-type-roominfo">';
                htmlBuffer = htmlBuffer + '<span title="' + room + '">' + room + '';
                htmlBuffer = htmlBuffer + '<var style="display: none;">…</var>';
                htmlBuffer = htmlBuffer + '</span>';
                htmlBuffer = htmlBuffer + '</a>';
                htmlBuffer = htmlBuffer + '</li>';
                htmlBuffer = htmlBuffer + '</ol>';
            }
            }
            $(".aui-dropdown").html(htmlBuffer);
            var _left = $("#searchBox").offset().left;
            var _width = "auto";
            $(".aui-dropdown").css("left", _left + "px");
            $(".aui-dropdown").slideDown("medium");
            //*** Build User Detials Modal Popup ***
            formatModalPopup();
            //*** Build Room Detials Modal Popup ***
            formatRoomModalPopup();
        }
        function HideSearchResults() {
            $(".aui-dropdown").html("");
            $(".aui-dropdown").hide();
        }
        function formatModalPopup() {
            var centeredY, centeredX, popupHeight, popupWidth;
            popupHeight = parseInt($("#modalbox").css("height"));
            popupWidth = parseInt($("#modalbox").css("width"));
            var screenW = screen.width;
            var screenH = screen.height;          
            //determine the top left coordinate to center the popup in
            var centeredX = (screenW / 2) - (popupWidth / 2);
            var centeredY = (screenH / 2) - (popupHeight / 2);
            //if the new window is larger than the screen, then offset it to the top left
            if (centeredX < 0 || centeredY < 0) 
            {
                centeredX = 0;
                centeredY = 0;
            } 
            //*** bind click event for user ***
            $(".content-type-userinfo").click(function() {
                if ($(".content people").css("display") == "none")
                    $(".content people").css("display", "block");
                
                var srcUrl = $(this).attr("href");
                var expvcpURL = srcUrl + "&action=exportvcf";
                var popupTitle = $(this).text().substring(0, $(this).text().indexOf(" -"));
                $("#aModalVcf").attr("href", expvcpURL);
                $("#frameUserDetails").attr("src", srcUrl);
                
                $('#frameUserDetails').load(function() {
                    this.style.height = this.contentWindow.document.body.offsetHeight + 30 + 'px';
                    this.style.width = '795px';
                    var modalheight = (parseInt($(this).css("height")) + 40) + 'px';
                    var modalwidth = (parseInt($(this).css("width")) + 10) + 'px';
                    $("#modalbox").css({ height: modalheight, width: modalwidth });
                });
                
                $(".modalbox_title_font").text("Details for " + popupTitle);
                $('#modalbox').jqmShow();
                return false;
            });
            
            $(".content-type-deptinfo").click(function(){
                FilterSearchRecord(this,1);
            });
            $(".content-type-jobinfo").click(function(){
                 FilterSearchRecord(this,2);
            });
        }
        
        function formatRoomModalPopup() {
          
            //*** bind click event for user ***
            $(".content-type-roominfo").click(function(e) {
                var srcUrl = $(this).attr("href");
                $("#frameRoom").attr("src", srcUrl);
                var modalheight, modalwidth;
                        $('#frameRoom').load(function() {
                    this.style.height = this.contentWindow.document.body.offsetHeight + 16 + 'px';
                    this.style.width = this.contentWindow.document.body.offsetWidth + 16 + 'px';
                    //alert($(this)[0].clientHeight + "\n" + this.contentWindow.document.body.offsetHeight);
                    modalheight = this.contentWindow.document.body.offsetHeight + 40 + 'px';
                    modalwidth = $(this)[0].clientWidth + 22 + 'px';
                });
                var centeredY, centeredX, popupHeight, popupWidth, firstroomLinkHt;
                popupHeight = parseInt($("#meeting_room").css("height"));
                popupWidth = parseInt($("#meeting_room").css("width"));
                if ($.browser.msie) {
                    centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120) / 2) - (popupHeight / 2)));
                    centeredX = window.screenLeft + ((((document.body.offsetWidth + 20) / 2) - (popupWidth / 2)));
                } else {
                    centeredY = window.screenY + (((window.outerHeight / 2) - (popupHeight / 2)));
                    centeredX = window.screenX + (((window.outerWidth / 2) - (popupWidth / 2)));
                }
                $("#meeting_room").css({ left: centeredX + "px", top: (centeredY - 100) + "px", height: modalheight, width: modalwidth });
                $('#meeting_room').jqmShow();
                return false;
            });
        }
        
        // treat up and down key strokes defining the next selected element
        function OnUpDownClick(keyCode) {
            if (keyCode == 40 || keyCode == 38) {
        
                if (keyCode == 38) { // keyUp
                    if (resultSelected == 0 || resultSelected == -1) {
                        resultSelected = resultCount - 1;
                    } else {
                        resultSelected--;
                    }
                } else { // keyDown
                    if (resultSelected == resultCount - 1) {
                        resultSelected = 0;
                    } else {
                        resultSelected++;
                    }
                }
        
                // loop through each result div applying the correct style
                $(".aui-dropdown > ol > li").children().each(function(i) {
                    if (i == resultSelected) {
                        $(this).parent()[0].className = "selected";
                        $(this).addClass("selected");
                        $(this).removeClass("unselected");
                    } else {
                        $(this).parent()[0].className = "unselected";
                        $(this).addClass("unselected");
                        $(this).removeClass("selected");
                    }
                });
        
                return true;
            } else {
                // reset
                resultSelected = -1;
                return false;
            }
        }
        
        function OnEnterClick() {
            $(".aui-dropdown").hide();
            if($(".aui-dropdown li").hasClass('selected')==false || $(".aui-dropdown li").hasClass('selected')=="false"){
                // only search when there are 3 or more characters in the textbox
                if($('#searchBox').val().length>2) {
                    // hide all rows
                    $('#tblDetails tr').hide();
                    // show the header row
                    $('#tblDetails tr:first').show();
                    // show the matching rows (using the containsNoCase)
                    $('#tblDetails tr td:containsNoCase(\''+$('#searchBox').val()+'\')').parent().show();
                }
                // if there were no matching rows, tell the user
                if($('#tblDetails tr:visible').length<=2) {
                    // remove the norecords row if it already exists
                    $('.norecords').remove();
                    // add the norecords row
                    $('#tblDetails').append('<tr class="norecords"><td colspan="5" class="Normal">No records were found</td></tr>');
                }
                //Paginate matched records
                //$("#tblDetails").tablePagination({});
                // show the cancel search image
                $('#imgSearch').show();
            }
            else{
                $("#searchBox").addClass("defaultTextActive");
                $("#searchBox").val($("#searchBox").attr("title"));
                $(".aui-dropdown > ol > li").children().each(function(i) {
                    if (i == resultSelected) {
                        if ($(this).hasClass("content-type-userinfo selected")) {
                            var srcUrl = $(this).attr("href");
                            var expvcpURL = srcUrl + "&action=exportvcf";
                            var popupTitle = $(this).text().substring(0, $(this).text().indexOf(" -"));
                            $("#aModalVcf").attr("href", expvcpURL);
                            $("#frameUserDetails").attr("src", srcUrl);
                            $('#frameUserDetails').load(function() {
                                this.style.height = this.contentWindow.document.body.offsetHeight + 30 + 'px';
                                this.style.width = '795px';
                                var modalheight = (parseInt($(this).css("height")) + 40) + 'px';
                                var modalwidth = (parseInt($(this).css("width")) + 10) + 'px';
                                $("#modalbox").css({ height: modalheight, width: modalwidth });
                            });
                            $(".modalbox_title_font").text("Details for " + popupTitle);
                            $('#modalbox').jqmShow();
        
                        }
                        else if ($(this).hasClass("content-type-roominfo selected")) {
                            var srcUrl = $(this).attr("href");
                            $("#frameRoom").attr("src", srcUrl);
                            var modalheight, modalwidth;
                            $('#frameRoom').load(function() {
                                this.style.height = this.contentWindow.document.body.offsetHeight + 16 + 'px';
                                this.style.width = this.contentWindow.document.body.offsetWidth + 16 + 'px';
                                modalheight = this.contentWindow.document.body.offsetHeight + 40 + 'px';
                                modalwidth = $(this)[0].clientWidth + 22 + 'px';
                            });
                            var centeredY, centeredX, popupHeight, popupWidth, firstroomLinkHt;
                            popupHeight = parseInt($("#meeting_room").css("height"));
                            popupWidth = parseInt($("#meeting_room").css("width"));
                            if ($.browser.msie) {
                                centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120) / 2) - (popupHeight / 2)));
                                centeredX = window.screenLeft + ((((document.body.offsetWidth + 20) / 2) - (popupWidth / 2)));
                            } else {
                                centeredY = window.screenY + (((window.outerHeight / 2) - (popupHeight / 2)));
                                centeredX = window.screenX + (((window.outerWidth / 2) - (popupWidth / 2)));
                            }
                            $("#meeting_room").css({ left: centeredX + "px", top: (centeredY - 100) + "px", height: modalheight, width: modalwidth });
                            $('#meeting_room').jqmShow();
                        }
                    }
                });
            }
        }
        function FilterSearchRecord(item,column){
         if($('#searchBox').val().length>2) {
                    // hide all rows
                    $('#tblDetails tr').hide();
                    // show the header row
                    $('#tblDetails tr:first').show();
                    // show the matching rows (using the containsNoCase)
                   $('#tblDetails tr td:containsNoCase(\''+$(item).text().slice(0,$(item).text().length-1)+'\')').parent().show();
                }
                // if there were no matching rows, tell the user
                if($('#tblDetails tr:visible').length<=2) {
                    // remove the norecords row if it already exists
                    $('.norecords').remove();
                    // add the norecords row
                    $('#tblDetails').append('<tr class="norecords"><td colspan="5" class="Normal">No records were found</td></tr>');
                }
                 //Paginate matched records
                    //$("#tblDetails").tablePagination({});
                      // show the cancel search image
                     $('#imgSearch').show();
                     $(".clearFilter:eq("+column+")").css("visibility", "visible");
                     return false;
        }
        function resetSearch() {
             // clear the textbox
             $('#searchBox').val('');
             // show all table rows
             var possibleTableRows=$.makeArray($('tbody tr',$("#tblDetails")));
             $(possibleTableRows).show();
             //$("#tblDetails").tablePagination({});
             // remove any no records rows
             $('.norecords').remove();
             // hide the cancel search image
             $('#imgSearch').hide();
             // make sure we re-focus on the textbox for usability
             $('#searchBox').focus();
             $(".clearFilter").css("visibility", "hidden");
         }
    };
})(jQuery);